package com.tianzeculture.stagebao.activity.login;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Paint;

import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;


import com.gun0912.tedpermission.PermissionListener;
import com.gun0912.tedpermission.TedPermission;
import com.tianzeculture.stagebao.R;
import com.tianzeculture.stagebao.activity.AgreementActivity;
import com.tianzeculture.stagebao.activity.BindPhoneActivity;

import com.tianzeculture.stagebao.activity.home.MainActivity;
import com.tianzeculture.stagebao.application.StageBaoApplication;
import com.tianzeculture.stagebao.base.BaseActivity;
import com.tianzeculture.stagebao.bean.LoginOtherBean;
import com.tianzeculture.stagebao.bean.User;
import com.tianzeculture.stagebao.bean.VersionBean;
import com.tianzeculture.stagebao.net.UserRestUsage;
import com.tianzeculture.stagebao.network.Request;
import com.tianzeculture.stagebao.network.enity.MSG;
import com.tianzeculture.stagebao.network.util.ToastUtil;
import com.tianzeculture.stagebao.util.SpUtils;
import com.tianzeculture.stagebao.util.Util;
import com.xiaoluo.updatelib.UpdateManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import de.hdodenhof.circleimageview.CircleImageView;


/**
 * Created by Administrator on 2018/5/23 0023.
 * 登录
 */

public class LoginActivity extends BaseActivity {

    private String huanxinTag = "huanxin";//环信Tag
    private int LOGIN = 101;

    @BindView(R.id.tvTitle)
    TextView tvTitle;

    @BindView(R.id.ivHead)
    CircleImageView ivHead;
    @BindView(R.id.tvPact)
    TextView tvPact;
    @BindView(R.id.tvFastRegister)
    TextView tvFastRegister;
    @BindView(R.id.tvForgetPwd)
    TextView tvForgetPwd;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    @BindView(R.id.edtPhone)
    EditText edtPhone;
    @BindView(R.id.edtPwd)
    EditText edtPwd;
    @BindView(R.id.check_tag)
    CheckBox checkTag;
    @BindView(R.id.img_QQ)
    ImageButton imgQQ;
    @BindView(R.id.img_WeiXin)
    ImageButton imgWeiXin;

    @Request
    UserRestUsage userRestUsage = null;

//    private int tokenId = 8;
//    private int getRongUserId = 9;

    private int loginCheckOtherId = 10;
    private int getVersionId = 7;
    private boolean isCheckTag;

    LoginOtherBean loginOtherBean = new LoginOtherBean();

    @Override



    protected int getLayoutResID() {
        return R.layout.activity_login;
    }

    @Override
    public void initUI() {
        super.initUI();
        StageBaoApplication.addActivity(this);

        tvTitle.setText(getString(R.string.login));
//        tvPact.setText(Html.fromHtml("<u>" + getString(R.string.pact) + "</u>"));
        tvPact.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tvPact.getPaint().setAntiAlias(true);//抗锯齿
        tvPact.setText(getString(R.string.pact));
        tvPact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginActivity.this, AgreementActivity.class));
            }
        });
        if ("1".equals((String) SpUtils.get(this, "contenthome", "0")))
            checkTag.setChecked(true);
        else checkTag.setChecked(false);
        if (!"0".equals((String) SpUtils.get(this, "userphone", "0")) && (String) SpUtils.get(this, "userphone", "0") != null)
            edtPhone.setText((String) SpUtils.get(this, "userphone", "0"));
        if (!"0".equals((String) SpUtils.get(this, "password", "0")) && (String) SpUtils.get(this, "userphone", "0") != null)
            edtPwd.setText((String) SpUtils.get(this, "password", "0"));
        userRestUsage.getVersion(getVersionId, new HashMap<String, String>());
        PermissionListener permissionlistener = new PermissionListener() {
            @Override
            public void onPermissionGranted() {
                ToastUtil.showShort(LoginActivity.this, "权限配置成功");
            }

            @Override
            public void onPermissionDenied(ArrayList<String> deniedPermissions) {

            }
        };
        new TedPermission(this).setPermissionListener(permissionlistener)
//                .setDeniedMessage("拒绝权限相关功能无法访问")
                .setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CALL_PHONE,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_SMS,
                        Manifest.permission.SEND_SMS,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                .check();


    }


    @OnClick(R.id.btnLogin)
    public void toMain(View view) {
        if (Util.isPhone(edtPhone.getText().toString().trim())) {
            if ("".equals(edtPwd.getText().toString().trim())) {
                ToastUtil.showShort(this, "密码不能为空!");
            } else if (!checkTag.isChecked()) {
                ToastUtil.showShort(this, "请阅读并同意舞台宝协议！");
            } else {
                showProgressDialog("正在登录...");
                userRestUsage.login(LOGIN, edtPhone.getText().toString().trim(), edtPwd.getText().toString().trim());
            }
        }

//        startActivity(new Intent(LoginActivity.this, AddTalentDataActivity.class));
//        startActivity(new Intent(LoginActivity.this, MainActivity.class));
    }

    @OnClick(R.id.tvFastRegister)
    public void toRegister(View view) {
        startActivity(new Intent(this, RegisterActivity.class));
    }

    @OnClick(R.id.tvForgetPwd)
    public void toForgetPwd(View view) {
        startActivity(new Intent(this, ForgetPwdActivity.class));
    }

    @OnClick(R.id.img_QQ)
    public void logByQQ(View view) {
        Platform qq = ShareSDK.getPlatform(QQ.NAME);
        if (qq.isAuthValid()) {
            qq.removeAccount(true);//执行此操作就可以移除掉本地授权状态和授权信息
        }
        qq.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                loginOtherBean.setAccount(platform.getDb().getUserId());
                loginOtherBean.setLoginType("2");
                loginOtherBean.setUsername(platform.getDb().getUserName());
                loginOtherBean.setUserSex("男".equals((hashMap.get("gender") + "")) ? "1" : "0");
                loginOtherBean.setUserArea(hashMap.get("city") + "");
                loginOtherBean.setUserHeader(hashMap.get("figureurl_2") + "");
                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("loginType", "2");
                paramMap.put("account", platform.getDb().getUserId());
//                paramMap.put("username ", platform.getDb().getUserName());
//                paramMap.put("userSex", "男".equals((hashMap.get("gender") + "")) ? "1" : "0");
//                paramMap.put("userArea", hashMap.get("city") + "");
//                paramMap.put("userHeader", hashMap.get("figureurl_2") + "");
                userRestUsage.loginCheckOther(loginCheckOtherId, paramMap);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {

            }

            @Override
            public void onCancel(Platform platform, int i) {

            }
        });
        qq.showUser(null);
    }

    @OnClick(R.id.img_WeiXin)
    public void logByWeiXin(View view) {
        Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
        if (wechat.isAuthValid()) {
            wechat.removeAccount(true);//执行此操作就可以移除掉本地授权状态和授权信息
        }
        wechat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                loginOtherBean.setAccount(platform.getDb().getUserId());
                loginOtherBean.setLoginType("1");
                loginOtherBean.setUsername(platform.getDb().getUserName());
                loginOtherBean.setUserSex(hashMap.get("sex") + "");
                loginOtherBean.setUserArea(hashMap.get("city") + "");
                loginOtherBean.setUserHeader(hashMap.get("headimgurl") + "");
                Map<String, String> paramMap = new HashMap<>();
                paramMap.put("loginType", "1");
                paramMap.put("account", platform.getDb().getUserId());
//                paramMap.put("username", platform.getDb().getUserName());
//                paramMap.put("userSex", hashMap.get("sex") + "");
//                paramMap.put("userArea", hashMap.get("city") + "");
//                paramMap.put("userHeader", hashMap.get("headimgurl") + "");
                userRestUsage.loginCheckOther(loginCheckOtherId, paramMap);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {

            }

            @Override
            public void onCancel(Platform platform, int i) {

            }
        });
        // true不使用SSO授权，false使用SSO授权
//        wechat.SSOSetting(false);
        wechat.showUser(null);
    }


    @Override
    public void refreshUI(int taskId, MSG msg) {
        super.refreshUI(taskId, msg);
        if (taskId == LOGIN) {
            ToastUtil.showShort(this, msg.getMessage());
            if (msg.getData()) {
                if (msg.getObj() != null) {
                    User user = (User) msg.getObj();
                    Util.user = user;
                    if (!"".equals(user.getUid())) {
                        Util.Uid = user.getUid();
                    }
                    if (!"".equals(user.getUserId()))
                        Util.UserId = user.getUserId();
                    Util.Token = user.getToken();
                    Util.JOB = user.getUserType();
                    Util.ALENT = user.getAlent();
                    Util.AuthenticationStatus = user.getStatus();
//                    startActivity(new Intent(this, MainActivity.class));
//                    StageBaoApplication.finishAllActivity();
                    SpUtils.put(this, "userphone", edtPhone.getText().toString().trim());
                    SpUtils.put(this, "password", edtPwd.getText().toString().trim());
                    SpUtils.put(this, "contenthome", "1");
                    startActivity(new Intent(this, MainActivity.class));
//                    userRestUsage.getToken(tokenId, user.getUserId());
                }
            }
            dismissProgressDialog();
        }
        if (taskId == loginCheckOtherId) {
            if (msg.getData()) {
                User user = (User) msg.getObj();
                if (user.getState() == 0) {
                    startActivity(new Intent(this, BindPhoneActivity.class).putExtra("data", loginOtherBean));
                } else {
                    Util.JOB = user.getUserType();
                    Util.UserId = user.getUserId();
                    Util.Token = user.getToken();
                    startActivity(new Intent(this, MainActivity.class));
                }
            }
        }
        if (taskId == getVersionId) {
            if (msg.getData()) {
                final VersionBean bean = (VersionBean) msg.getObj();
                if (bean.getVersionNumber() > getLocalVersion(this)) {
                    UpdateManager.getInstance().init(this)
                            .downloadUrl("http://" + bean.getDownloadLink())
                            .lastestVerCode(bean.getVersionNumber())
                            .update();
                }
            }
        }

    }


    /**
     * 获取本地软件版本号
     */

    public static int getLocalVersion(Context ctx) {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }

}
